package com.fitapp;

import gui.SportsArrayAdapter;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.TimeZone;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.plus.PlusShare;

public class MainActivity extends Activity
{
	private ListView lvSports;
	private RelativeLayout linearChart;
	private String[ ] elementArray;
	private ArrayList< Integer > ids;
	private Toast lastToast;

	@Override
	protected void onCreate( Bundle savedInstanceState )
	{
		super.onCreate( savedInstanceState );
		setContentView( R.layout.activity_main ); // Connect gui
		lvSports = (ListView) findViewById( R.id.lvSports );
	}

	protected void onResume()
	{
		super.onResume( );

		// CHART
		linearChart = (RelativeLayout) findViewById( R.id.linearChart );
		linearChart.setOnTouchListener( new View.OnTouchListener( )
		{

			@Override
			public boolean onTouch( View arg0, MotionEvent arg1 )
			{
				Intent i = new Intent( MainActivity.this, StatsActivity.class );
				startActivity( i );
				MainActivity.this.onDestroy( );
				return false;
			}
		} );
		drawChart( 5 );
		ArrayList< String > elements = new ArrayList< String >( );
		ids = new ArrayList< Integer >( );
		ArrayList< Integer > dates = new ArrayList< Integer >( );
		DatabaseHelper helper = new DatabaseHelper( this );
		SQLiteDatabase db = helper.getReadableDatabase( );
		Cursor cursor = db.rawQuery( "SELECT * FROM Activities ORDER BY date DESC LIMIT 10", null );
		if( cursor.getCount( ) > 0 )
		{
			cursor.moveToFirst( );
			do
			{
				Calendar mydate = Calendar.getInstance( TimeZone.getTimeZone( TimeZone.getDefault( ).getID( ) ) );
				mydate.setTimeInMillis( (long) cursor.getInt( 2 ) * 1000 );
				dates.add( cursor.getInt( 2 ) * 1000 );
				String type = "";

				// Set images according to activity
				if( cursor.getString( 1 ).equals( DatabaseHelper.TYPE_RUNNING ) )
				{
					type = "Jogging";
				}
				else if( cursor.getString( 1 ).equals( DatabaseHelper.TYPE_BENDING ) )
				{
					type = "Banding";
				}
				else if( cursor.getString( 1 ).equals( DatabaseHelper.TYPE_PRESSUP ) )
				{
					type = "Pressups";
				}
				else if( cursor.getString( 1 ).equals( DatabaseHelper.TYPE_SITUP ) )
				{
					type = "Situps";
				}

				ids.add( Integer.parseInt( cursor.getString( 0 ) ) );
				String a = "";
				if( mydate.get( Calendar.MINUTE ) < 10 )
				{
					a = "0";
				}

				// Buid string for listview
				String listText = mydate.get( Calendar.DAY_OF_MONTH ) + "." + ( mydate.get( Calendar.MONTH ) + 1 ) + " at " + mydate.get( Calendar.HOUR_OF_DAY ) + ":" + a + mydate.get( Calendar.MINUTE ) + " - " + type + " (" + cursor.getString( 4 );

				// Switch output according to activity
				if( type.equals( "Jogging" ) )
				{
					listText += "m)";
				}
				else
				{
					listText += " recaps)";
				}

				elements.add( listText ); // Add to elements for listview
			}
			while( cursor.moveToNext( ) );
			cursor.close( );
		}
		elementArray = elements.toArray( new String[ elements.size( ) ] );
		SportsArrayAdapter adapter = new SportsArrayAdapter( this, R.layout.listview_item_row, elementArray );
		lvSports.setAdapter( adapter );
		// lvSports.setOnItemClickListener( null );
		OnItemClickListener oicl = new OnItemClickListener( )
		{
			@Override
			public void onItemClick( AdapterView< ? > arg0, View arg1, int arg2, long arg3 )
			{
				openActivity( arg2 );
			}
		};
		lvSports.setOnItemClickListener( oicl );
	}

	public void openActivity( int act )
	{

		if( elementArray[ act ].contains( "Jogging" ) )
		{
			Intent intent = new Intent( MainActivity.this, RunActivity.class );
			intent.putExtra( "methodName", "printOld" );
			intent.putExtra( "id", ids.get( act ) );
			startActivity( intent );
		}
		else if( elementArray[ act ].contains( "Banding" ) )
		{
			Intent intent = new Intent( MainActivity.this, HistoryWorkout.class );
			intent.putExtra( "type", "Bending" );
			intent.putExtra( "id", ids.get( act ) );
			startActivity( intent );
		}
		else if( elementArray[ act ].contains( "Pressups" ) )
		{
			Intent intent = new Intent( MainActivity.this, HistoryWorkout.class );
			intent.putExtra( "type", "Pressups" );
			intent.putExtra( "id", ids.get( act ) );
			startActivity( intent );
		}
		else if( elementArray[ act ].contains( "Situps" ) )
		{
			Intent intent = new Intent( MainActivity.this, HistoryWorkout.class );
			intent.putExtra( "type", "Situps" );
			intent.putExtra( "id", ids.get( act ) );
			startActivity( intent );
		}
	}

	public void onBtnRunClicked( View view )
	{
		Intent i = new Intent( MainActivity.this, RunActivity.class );
		startActivity( i );
		MainActivity.this.onDestroy( );
	}

	public void onBtnSportClicked( View view )
	{
		Intent i = new Intent( MainActivity.this, SportActivity.class );
		startActivity( i );
		MainActivity.this.onDestroy( );
	}

	public void onBtnPressUpClicked( View view )
	{
		Intent i = new Intent( MainActivity.this, LightSensorSportArtsActivity.class );
		startActivity( i );
		i.putExtra( "modus", DatabaseHelper.TYPE_PRESSUP );
		MainActivity.this.onDestroy( );
	}

	public void onBtnSitUpClicked( View view )
	{
		Intent i = new Intent( MainActivity.this, LightSensorSportArtsActivity.class );
		i.putExtra( "modus", DatabaseHelper.TYPE_SITUP );
		startActivity( i );
		MainActivity.this.onDestroy( );
	}

	/**
	 * Creates the ActionBar in the Activity
	 * 
	 */
	@Override
	public boolean onCreateOptionsMenu( Menu menu )
	{
		// Inflate the menu items for use in the action bar
		MenuInflater inflater = getMenuInflater( );
		inflater.inflate( R.menu.main, menu );
		return super.onCreateOptionsMenu( menu );
	}

	/**
	 * The System calls this function as soon somebody clicks on the ActionBar
	 * 
	 */
	public boolean onOptionsItemSelected( MenuItem item )
	{
		// Takes care about the clicks
		switch( item.getItemId( ))
		{
			case R.id.shareButton:
				DatabaseHelper helper = new DatabaseHelper( this );
				SQLiteDatabase db = helper.getReadableDatabase( );
				Cursor cursor = db.rawQuery( "SELECT * FROM Activities ORDER BY date DESC LIMIT 1", null );
				cursor.moveToFirst( );
				if( cursor.getCount( ) <= 0 )
				{
					showToast( "Do your first WorkOut! Lazy bugger!!" );
					return true;
				}

				// Convert the data from int to correct date values
				ArrayList< Integer > dates = new ArrayList< Integer >( );
				Calendar mydate = Calendar.getInstance( TimeZone.getTimeZone( TimeZone.getDefault( ).getID( ) ) );
				mydate.setTimeInMillis( (long) cursor.getInt( 2 ) * 1000 );
				dates.add( cursor.getInt( 2 ) * 1000 );

				// Get the Data from the Database
				String message = "";
				String message1 = "I did a great Workout in ";
				String message2 = " and it took me ";
				String message3 = " seconds. ";
				String message4 = "I have done it in the past time (";
				String message5 = ") with ";
				String message6 = " Iterations. Congratulations to myself";
				String type;
				String time;
				String date;
				String count;

				cursor.moveToFirst( );
				type = cursor.getString( 1 );
				date = mydate.get( Calendar.DAY_OF_MONTH ) + "." + ( mydate.get( Calendar.MONTH ) + 1 ) + "." + mydate.get( Calendar.YEAR ) + " at " + mydate.get( Calendar.HOUR_OF_DAY ) + ":" + mydate.get( Calendar.MINUTE );
				;
				time = cursor.getString( 3 );
				count = cursor.getString( 4 );
				cursor.close( );

				// Parse the message according to the Type
				if( DatabaseHelper.TYPE_BENDING.equals( type ) )
				{
					message = message1 + "bending" + ". " + message4 + date + message5 + count + message6;
				}
				else if( DatabaseHelper.TYPE_PRESSUP.equals( type ) )
				{
					message = message1 + "press ups" + ". " + message4 + date + message5 + count + message6;
				}
				else if( DatabaseHelper.TYPE_RUNNING.equals( type ) )
				{
					message = message1 + "jogging" + message2 + time + message3 + message4 + date + message5 + count + " Kilometers. Congratulations to myself";
				}
				else if( DatabaseHelper.TYPE_SITUP.equals( type ) )
				{
					message = message1 + "sit ups" + ". " + message4 + date + message5 + count + message6;
				}

				// Launch the Google+ share dialog with attribution to your app.
				Intent shareIntent = new PlusShare.Builder( this ).setType( "text/plain" ).setText( "My great Workout!! \n " + message ).setContentUrl( Uri.parse( "http://srv14.comtec.e-technik.uni-kassel.de/cc1/?L=1" ) ).getIntent( );
				startActivityForResult( shareIntent, 0 );
		}
		return true;
	}

	public void showToast( String text )
	{
		if( lastToast != null )
		{
			lastToast.cancel( );
		}
		lastToast = Toast.makeText( MainActivity.this, text, Toast.LENGTH_SHORT );
		lastToast.show( );
	}

	@SuppressWarnings( value = { "deprecation" } )
	public void drawChart( int count )
	{

		Display display = getWindowManager( ).getDefaultDisplay( );
		DisplayMetrics outMetrics = new DisplayMetrics( );
		display.getMetrics( outMetrics );
		DatabaseHelper helper = new DatabaseHelper( this );
		SQLiteDatabase db = helper.getWritableDatabase( );
		Cursor cursor = db.rawQuery( "SELECT * FROM Goals ORDER BY Intended DESC", null );

		int i = 1;
		View acc = null;
		Resources res = getResources( );
		if( cursor.getCount( ) > 0 )
		{
			cursor.moveToFirst( );
			double max = 0;

			// Dirty
			do
			{
				String type = cursor.getString( 1 );
				double reachedVal = Double.parseDouble( cursor.getString( 3 ) );
				// int reachedVal = Integer.parseInt(cursor.getString( 3 ));
				double intendedVal = Double.parseDouble( cursor.getString( 4 ) );
				if( intendedVal > max )
				{
					max = intendedVal;
				}

				TextView tv = new TextView( this );
				tv.setText( type );
				tv.setTextColor( Color.parseColor( "#000000" ) );
				tv.setTypeface( null, Typeface.BOLD );
				tv.setShadowLayer( 1.5f, -1, 1, Color.LTGRAY );
				RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams( (int) ( ( intendedVal / max ) * outMetrics.widthPixels ), ( (int) outMetrics.heightPixels / 160 ) * 5 );
				if( i != 1 )
					p.addRule( RelativeLayout.BELOW, acc.getId( ) );
				p.setMargins( 15, 0, 10, (int) outMetrics.heightPixels / 160 * 1 );
				tv.setLayoutParams( p );
				View view = new View( this );
				view.setId( i );
				view.setBackgroundColor( Color.parseColor( "#6b9eb4" ) );
				Drawable shape = res.getDrawable( R.drawable.bar );
				view.setBackgroundDrawable( shape );
				RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams( (int) ( ( intendedVal / max ) * outMetrics.widthPixels ), ( (int) outMetrics.heightPixels / 160 ) * 5 );
				if( i == 1 )
					params.addRule( RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE );
				if( i != 1 )
					params.addRule( RelativeLayout.BELOW, acc.getId( ) );
				params.setMargins( 10, 0, 10, 0 );
				view.setLayoutParams( params );
				linearChart.addView( view );
				linearChart.addView( tv );
				View view1 = new View( this );
				view1.setId( i + 1 );
				view1.setBackgroundColor( Color.parseColor( "#84a40b" ) );
				shape = res.getDrawable( R.drawable.bar_success );
				view1.setBackgroundDrawable( shape );
				System.out.println( "REACHED:" + reachedVal );
				RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams( (int) ( ( reachedVal / max ) * outMetrics.widthPixels ), ( (int) outMetrics.heightPixels / 160 ) * 2 );
				params1.addRule( RelativeLayout.BELOW, view.getId( ) );
				params1.setMargins( 10, 0, 10, (int) outMetrics.heightPixels / 160 * 1 );
				view1.setLayoutParams( params1 );
				linearChart.addView( view1 );
				i += 2;
				acc = view1;
			}
			while( cursor.moveToNext( ) ); // TODO
		}
	}
}
